<?php


namespace app\api\controller;


use app\common\controller\Api;
use think\Request;
use think\Db;

class Exchange extends Api
{
    protected $noNeedLogin = ['*'];

    public function do(Request $request)
    {
        if (!$request->isPost()) {
            $this->error('ＤＯＮ＇Ｔ　ＧＥＴ');
        }
        $exchange = new \app\admin\model\Exchange();
        $req = $request->post();
        $user = $this->auth->getUserinfo();

        $find = $exchange->where('code', $req['code'])->find();
        if (!$find) {
            $this->error('兑换码不存在', '', 101);
        }
        if ($find['status'] == 'deleted') {
            $this->error('兑换码已失效', '', 102);
        }
        if ($find['status'] == 'used') {
            $this->error('兑换码已用', '', 103);
        }
        $exchange->startTrans();
        $res = $exchange->where('code', $req['code'])->update(['status' => 'used', 'userid' => $user['id']]);
        if ($res) {
            $time = 0;
            if ($find['class'] == 'month') {
                //月卡
                $time = 30;
            }
            if ($find['class'] == 'season') {
                //季度
                $time = 90;
            }
            if ($find['class'] == 'halfyear') {
                //半年
                $time = 180;
            }
            if ($find['class'] == 'year') {
                //年卡
                $time = 360;
            }
            if ($user['vip_time'] > time()) {
                //没到期时间
                $time = $user['vip_time'] + ($time * 86400);
            } else {
                //到期时间
                $time = time() + ($time * 86400);
            }
            $res = db::table('fa_user')->where('id', $user['id'])->update(['vip_time' => $time]);
            if ($res) {
                $exchange->commit();
                $this->success('兑换成功', '', 200);
            } else {
                $exchange->rollback();
                $this->success('失败', '', 0);

            }
        }
    }

}
